package com.xsz.pda.ui

import android.app.Activity
import android.content.Context
import android.content.Intent
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.ThreadUtils
import com.xsz.pda.App
import com.xsz.pda.AppExecutors
import com.xsz.pda.Config
import com.xsz.pda.data.bean.TicketInfo
import com.xsz.pda.data.bean.ValidateTicket
import com.xsz.pda.data.model.TicketModel
import com.xsz.pda.device.nfc.NFCReader
import com.xsz.pda.device.qrcode.QrcodeReader
import com.xsz.pda.utils.SoundPoolUtil
import com.xsz.pda.net.mq.MyMqttClient
import java.lang.ref.WeakReference

class MainPresenter(private val view: MainContract.View): MainContract.Presenter {


//    private val queryTimesTask = Thread({
//        try {
//            Thread.sleep(1500)
//            while (true) {
//                ticketModel.getCheckCount().apply {
//                    view.showCheckCount("$first", "$second")
//                }
//                view.showNetStatus(EmqConn(mq.isOnline()))
//                Thread.sleep(500)
//            }
//        } catch (e: Exception) {
//            Log.e("MainPresenter",e.message, e)
//            // 线程结束
//        }
//
//    },"checkCountThread")

    private val soundUtil = SoundPoolUtil(view as Context)
    private val qrcodeReader = QrcodeReader(WeakReference(view as Activity))


    private  var nfcReader: NFCReader = NFCReader(view as Context)


    private val mq = MyMqttClient(
        view as Context,
        DeviceUtils.getAndroidID(),
        Config.getProjectId()
    )

    override fun init() {
        qrcodeReader.init()
        TicketModel.start()
        App.ticketTypes = Config.getTicketTypeIds()
        App.groupId= Config.getGroupId()
        AppExecutors.diskIO.execute{
            Thread.sleep(2500)
            mq.connectEmq()
        }
        qrcodeReader.setOnScanListener(object :QrcodeReader.OnScanListener{
            override fun onScan(qrcode: String) {
                AppExecutors.diskIO.execute {
                    view.showTicket(TicketInfo(qrcode,"",""),"","","",0)
                    TicketModel.check(qrcode, null,null).apply {
                        play(third)
                        if (first != null) {
                            val groupName = first!!.lastInGroup
                            val lastInTime = first!!.lastInTime
                            view.showTicket(TicketInfo(qrcode,"",""), groupName, lastInTime, "验证成功", 1)
                        }else{
                            view.showTicket(TicketInfo(qrcode,"",""), "", "", second, 2)
                        }
                    }
                }
            }
        })
        if(!App.checkIdCard) {
            nfcReader.setOnReadListener {
                view.showTicket(TicketInfo("", it,""), "", "", "", 0)
                ThreadUtils.executeByIo(object :
                    ThreadUtils.Task<Triple<ValidateTicket?, String, Int>>() {
                    override fun doInBackground(): Triple<ValidateTicket?, String, Int> {
                        return TicketModel.check(null, it, null)
                    }

                    override fun onSuccess(result: Triple<ValidateTicket?, String, Int>) {
                        result.apply {
                            play(result.third)
                            if (first != null) {
                                val groupName = first!!.lastInGroup
                                val lastInTime = first!!.lastInTime
                                val seat = first!!.seat
                                view.showTicket(
                                    TicketInfo("", it, seat),
                                    groupName,
                                    lastInTime,
                                    "验证成功",
                                    1
                                )
                            } else {
                                view.showTicket(TicketInfo("", it,""), "", "", second, 2)
                            }
                        }
                    }

                    override fun onCancel() {}
                    override fun onFail(t: Throwable?) {}
                })
            }
        }
//        queryTimesTask.start()
    }

    private fun play(type: Int) {
        when (type) {
            0 ->        soundUtil.play(SoundPoolUtil.YZCG)
            1 ->        soundUtil.play(SoundPoolUtil.WXPZ)
            2 ->        soundUtil.play(SoundPoolUtil.RCKCW)
            3 ->        soundUtil.play(SoundPoolUtil.RCSJCW)
            4 ->        soundUtil.play(SoundPoolUtil.CSYW)
            else ->     soundUtil.play(SoundPoolUtil.YZSB)
        }
    }

    override fun release() {
//        queryTimesTask.interrupt()
        TicketModel.stop()
        qrcodeReader.release()
        soundUtil.release()
        mq.release()
    }

    override fun onResume(){
        if(!App.checkIdCard) {
            nfcReader.touch()
        }
    }

    override fun parseNfc(intent: Intent) {
        if(!App.checkIdCard) {
            nfcReader.parse(intent)
        }
    }

    override fun checkIdCard(idNumber: String, name: String) {

        AppExecutors.diskIO.execute {
            TicketModel.check(null, null, idNumber).apply {
                play(third)
                if (first != null) {
                    val groupName = first!!.lastInGroup
                    val lastInTime = first!!.lastInTime
                    val seat = first!!.seat
                    view.showTicket(
                        TicketInfo(name, idNumber, seat),
                        groupName,
                        lastInTime,
                        "验证成功",
                        1
                    )
                } else {
                    view.showTicket(TicketInfo(name, idNumber, ""), "", "", second, 2)
                }
            }
        }
    }
}